# GPL v3 or later

import os
import time
from modules.ui import *
from modules import youtube
import subprocess

center("Album Getter")


# Main loop
while True:
    c = input(" > ")


    if c in ["exit", "quit"]:
        break

    elif c:
        data_print = {"categories":["Name of Album", "Publisher", "Amount of Songs"],
                          "size":[5,2,1],
                          "data":[]}
        listis = []
        
        for i in youtube.search(c):
            if i.get("type") == "playlist":

                listis.append(i)
                
                name = i.get("title", "")
                publisher = i.get("author", "")
                amount = i.get("videoCount", "")
                data_print["data"].append([name, publisher, amount])



                #playlist =  youtube.fetch_playlist(i.get("playlistId"))

                

                
                #print(playlist)

        while True:
            table(data_print)
            center("Choose an Album by number")
            alc = input(" >> ")

            if not alc:
                break
            
            try:
                alc = int(alc)
                playlist =  youtube.fetch_playlist(listis[alc].get("playlistId"))
                playlistName = playlist.get("title", c)
                songs_print = {"categories":["Song", "Duration"],
                          "size":[5,1],
                          "data":[]}
                IDS = []
                names = []
                for song in playlist.get("videos", []):
                    name = song.get("title", "")
                    names.append(name)
                    duration = song.get("lengthSeconds", 0)
                    ID = song.get("videoId", "")
                    IDS.append(ID)
                    songs_print["data"].append([name, timestring(duration)])


                table(songs_print, False)
                center("Download Yes / No ?")
                yesno = input(" >>> ")
                print()
                if yesno.lower().startswith("y"):

                    download_dir = os.path.expanduser("~/Downloads/"+playlistName+"/")
                    try:
                        os.makedirs(download_dir)
                    except:
                        pass
                    
                    for n, ID in enumerate(IDS):
                        progress_bar(n, len(IDS), "Downloading "+names[n])
                        youtube.insure_song(ID, download_dir+str(n+1)+" - "+names[n])

                    subprocess.Popen(["xdg-open", download_dir])
                    print()
                    print()
            except Exception as e:
                print(e)
        
